import cv2
import numpy as np

img  = cv2.imread('combo.png')
pts = np.array([[310,364],[340,364],[310,454],[340,454]], np.int32)   # 你的 4 点

# 1. 建掩膜
mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.fillPoly(mask, [pts], 255)

# 2. 提取彩色区域
res  = cv2.bitwise_and(img, img, mask=mask)

# 3. 生成 alpha 通道：掩膜区域 255，其余 0
b,g,r = cv2.split(res)
alpha = mask

# 4. 拼成 BGRA
bgra  = cv2.merge([b,g,r,alpha])

# 5. 最小外接矩形裁剪
x,y,w,h = cv2.boundingRect(pts)
cropped = bgra[y:y+h, x:x+w]

cv2.imwrite('skew_roi.png', cropped)   # 背景透明


# 在原图上画 ROI 框，看位置对不对
cv2.rectangle(img, (310,374), (340,454), (0, 255, 0), 2)
cv2.imshow('check ROI', img)
cv2.waitKey(0)


roi = cv2.imread('skew_roi.png', cv2.IMREAD_UNCHANGED)
h,w = roi.shape[:2]
gray = cv2.cvtColor(roi[:,:,:3], cv2.COLOR_BGR2GRAY)

# 掩膜：只考虑原斜矩形内部
valid = roi[:,:,3] > 0
black = (gray < 80) & valid

# 按列求黑色像素的 y 坐标平均值 → 中心线
centers = []
for x in range(w):
    col_y = np.where(black[:,x])[0]
    if col_y.size:
        centers.append((x, int(col_y.mean())))
centers = np.array(centers)          # shape (N,2)

# 可视化
show = roi.copy()
for x,y in centers:
    cv2.circle(show, (x,y), 1, (0,0,255,255), -1)
    # 假设你要显示的图是 `show`
zoom = 10
big = cv2.resize(show, None, fx=zoom, fy=zoom, interpolation=cv2.INTER_NEAREST)
cv2.imshow('black_center_line', big)
cv2.imwrite('black_line.png', big)
cv2.waitKey(0)


